package cn.harry.wx.service.impl;

import cn.harry.config.TaskExcutor;
import cn.harry.wx.dao.WxMsgTemplateDao;
import cn.harry.wx.entity.WxMsgTemplate;
import cn.harry.wx.entity.WxTemplateMsgLog;
import cn.harry.wx.service.WxAccountService;
import cn.harry.wx.service.WxMsgTemplateService;
import cn.harry.wx.service.WxTemplateMsgLogService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息模板
 *
 * @author honghh
 * Date 2021-04-08 16:19:27
 * Copyright (C) www.tech-harry.cn
 */
@Service("wxMsgTemplateService")
@RequiredArgsConstructor
public class WxMsgTemplateServiceImpl extends ServiceImpl<WxMsgTemplateDao, WxMsgTemplate> implements WxMsgTemplateService {
    @Autowired
    private WxTemplateMsgLogService templateMsgLogService;
    private final WxMpService wxService;
    @Resource
    private WxAccountService wxAccountService;

    @Override
    public IPage<WxMsgTemplate> getPage(WxMsgTemplate wxMsgTemplate, Integer pageSize, Integer pageNum) {
        LambdaQueryWrapper<WxMsgTemplate> wrapper = new LambdaQueryWrapper<>(wxMsgTemplate);

        if (StrUtil.isNotEmpty(wxMsgTemplate.getBeginTime())) {
            wrapper.gt(WxMsgTemplate::getCreateTime, wxMsgTemplate.getBeginTime());
        }
        if (StrUtil.isNotEmpty(wxMsgTemplate.getEndTime())) {
            wrapper.lt(WxMsgTemplate::getCreateTime, wxMsgTemplate.getEndTime());
        }
        return page(new Page<>(pageNum, pageSize), wrapper);
    }


    @Override
    public WxMsgTemplate selectById(Long id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public int create(WxMsgTemplate wxMsgTemplate) {
        return this.baseMapper.insert(wxMsgTemplate);
    }


    @Override
    public int update(Long id, WxMsgTemplate wxMsgTemplate) {
        wxMsgTemplate.setId(id);
        return this.baseMapper.updateById(wxMsgTemplate);
    }


    @Override
    public int deleteByIds(Long[] ids) {
        return this.baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 发送微信模版消息,使用固定线程的线程池
     */
    @Override
    @Async
    public void sendTemplateMsg(WxMpTemplateMessage msg, String appid) {
        TaskExcutor.submit(() -> {
            String result;
            try {
                wxService.switchover(appid);
                result = wxService.getTemplateMsgService().sendTemplateMsg(msg);
            } catch (WxErrorException e) {
                result = e.getMessage();
            }
            //保存发送日志
            WxTemplateMsgLog log = new WxTemplateMsgLog(msg, appid, result);
            templateMsgLogService.addLog(log);
        });
    }
    @Override
    public void syncWxTemplate(String appid) throws WxErrorException {

        // todo 此处会有重复数据插入时报错问题
        List<WxMpTemplate> wxMpTemplateList= wxService.getTemplateMsgService().getAllPrivateTemplate();
        List<WxMsgTemplate> templates = wxMpTemplateList.stream().map(item->new WxMsgTemplate(item,appid)).collect(Collectors.toList());
        this.saveBatch(templates);
    }

}